package database

import (
	"fmt"
	"multi-cloud-manage/config"
	"multi-cloud-manage/internal/model"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

// 连接数据库，执行迁移
func InitDB() (*gorm.DB, error) {
	// 获取配置信息
	cfg := config.GetConfig()
	// 创建连接
	dsn := fmt.Sprintf(
		"%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.Database.User,
		cfg.Database.Password,
		cfg.Database.Host,
		cfg.Database.Port,
		cfg.Database.Dbname,
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}
	fmt.Println("连接成功：", db)
	// 迁移
	err = db.AutoMigrate(
		&model.User{},
		&model.UserCredentials{},
		&model.Ecs{},
	)
	if err != nil {
		return nil, err
	}
	return db, nil
}
